# 定义一个全局变量，用来保存学生的信息，方法各个函数之间进行访问
import ntpath

import os


students = []

# 菜单函数
def menu():
    print("****************************************")
    print("*				学生管理系统			 *")
    print("*  	    1. 添加新学生信息              *")
    print("* 	    2. 通过学号修改学生信息		 *")
    print("*		3. 通过学号删除学生信息		 *")
    print("*		4. 通过姓名删除学生信息		 *")
    print("* 	    5. 通过学号查询学生信息          *")
    print("*		6. 通过姓名查询学生信息          *")
    print("*		7. 显示所有学生信息             *")
    print("*		8. 退出系统			  		 *")
    print("****************************************")
    select_op = input("输入编号选择操作：")
    return select_op

# 获取学号
def getSid():
    sid = input("请输入学生ID:")
    return sid

# 获取姓名
def getName():
    name = input("请输入学生姓名：")
    return name

# 获取年龄
def getAge():
    while True:
        age = input("请输入学生年龄：")
        if age.isdigit():
            return int(age)
        else:
            print("输入年龄不合法，请输入数字")

# 获取性别
def getGender():
    gender = input("请输入学生性别：")
    return gender

# 添加学生
def addStudent(sid, name, age, gender):
    # print(students)
    for s in students:
        if s["sid"] == sid:
            print("学号已存在，添加失败")
            return "添加失败"
    else:
        student = {"sid": sid, "name": name, "age": age, "gender": gender}
        students.append(student)
        print("添加学生信息成功")
        # print(students)
        return '添加成功'

# 通过学号修改学生信息
def modifyStudentByID(sid):
    for s in students:
        if s["sid"] == sid:
            name = getName()
            age = getAge()
            gender = getGender()
            s["name"] = name
            s["age"] = age
            s["gender"] = gender
            print("修改成功")
            return "修改成功"
    else:
        print(f'没有 {sid} 对应的学生信息')
        return "修改失败"

# 通过ID删除学生信息
def deleteStudentByID(sid):
    for s in students:
        if s["sid"] == sid:
            students.remove(s)
            print("删除成功")
            return "删除成功"
    else:
        print(f'没有 {sid} 对应的学生信息')
        return "删除失败"

# 通过学生姓名 删除所有符合的学生
def deleteStudentByName(name):
    exist_s = []
    # 找出所有要删除的学生
    for s in students:
        if s['name'] == name:
            exist_s.append(s)

    # 开始删除
    if len(exist_s) > 0:
        for s in exist_s:
            students.remove(s)
            print(f"学号 { s['sid'] } 的学生删除成功")
        else:
            print(f"成功删除 {len(exist_s)} 个学生")
            return "删除成功"
    else:
        print("学号不存在，无法删除")
        return "删除失败"

# 通过学号查询学生信息
def queryStudentByID(sid):
    for s in students:
        if s["sid"] == sid:
            print(f"学号 {sid} 的学生信息如下：")
            print(s)
            return "查询成功"
    else:
        print(f"学号 {sid} 的学生不存在")
        return "查询失败"

# 通过姓名查询学生信息
def queryStudentByName(name):
    result = []
    for s in students:
        if s["name"] == name:
            result.append(s)

    if len(result) > 0:
        print(f"姓名为 {name} 的学生共 {len(result)} 名，信息如下：")
        for s in result:
            print(s)
        return "查询成功"
    else:
        print(f"姓名为 {name} 的学生不存在")
        return "查询失败"

# 显示所有学生信息
def showAllInfo():
    print("所有学生信息如下：")
    for s in students:
        print(s)

# 管理函数
def studentManager():
    # try:
    #     with open('nonexistent_file.txt', 'r') as file:
    #         content = file.read()
    #         print(content)
    # except FileNotFoundError:
    #     print('文件不存在，无法读取。')

    # 执行文件操作
    try:
        file_name = "data.txt"
        with open( file_name, "r") as file:
            file_content = file.read()
            dictionary = eval(file_content)
            students.extend(dictionary)
            # print(f"加载文件不存在：{file_name}")
        # print(f"文件内容：\n{dictionary}")
        print(f"文件内容已加载：{file_name}")
    except FileNotFoundError:
        print(f'文件 {file_name} 不存在，正在创建该文件...')

        with open(file_name, 'w') as file:
             pass
        print(f'文件 {file_name} 已创建。')


    while True:
        select_op = menu()
        if len(select_op) == 1 and select_op in "12345678":
            if select_op == "1":
                sid = getSid()
                name = getName()
                age = getAge()
                gender = getGender()
                addStudent(sid, name, age, gender)
            elif select_op =="2":
                sid = getSid()
                modifyStudentByID(sid)
            elif select_op =="3":
                sid = getSid()
                deleteStudentByID(sid)
            elif select_op =="4":
                name = getName()
                deleteStudentByName(name)
            elif select_op =="5":
                sid = getSid()
                queryStudentByID(sid)
            elif select_op =="6":
                name = getName()
                queryStudentByName(name)
            elif select_op =="7":
                showAllInfo()
            else:
                Student_Information = str(students)
                file_name = "data.txt"
                with open(file_name, "w") as file:
                    file.write(Student_Information)
                    print(f"内容已写入文件：{file_name}")


                break

        else:
            print("输入的数据不合法，请输入在合法范围内的操作编号！！！")

# 程序入口
if __name__ == '__main__':
    studentManager()